from bs4 import BeautifulSoup  # 网页解析，获取数据
import re  # 正则表达式，进行文字匹配
import urllib.request, urllib.error  # 制定url，获取网页数据
import xlwt  # 进行Excel操作
import sqlite3  # 进行sqlite数据库操作


def main():
    baseurl = "https://movie.douban.com/top250?start="
    # 1.爬取网页
    datalist = getdate(baseurl)
    # print(datalist)
    print(askurl('https://movie.douban.com/top250?start='))
    # 3.保存数据
    # savepath = "豆瓣电影Top250.xls"  # 保存文件系统
    # savedata(datalist, savepath)


# 影片链接
findlist = re.compile(r'<a href=(.*?)">')  # 影片规则
# 影片图片的链接
findimgsrc = re.compile(r'<img.*src="(.*?)"', re.S)  # re.S让换行符包含在字符中
# 影片名
findtitle = re.compile(r'<span class="title">(.*)</span>')
# 影片评分
findpingfen = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
# 影片评价人数
findpeople = re.compile(r'<span>(\d*)人评价</span>')
# 网页概况
findgaikuang = re.compile(r'<span class="inq">(.*)</span>')
# 找到影片的相关内容
findcontent = re.compile(r'<p class="">(.*?)</p>', re.S)


# 爬取网页
def getdate(baseurl):
    datalist = []
    for i in range(0, 10):
        url = baseurl + str(i * 25)
        html = askurl(url)  # 保存获取到的网页源码
        # print(html)
        # 2.逐一解析数据
        soup = BeautifulSoup(html, "html.parser")  # 对网页源码进行解析
        for item in soup.find_all('div', class_="item"):  # 查找符合要求的字符串，形成列表
            data = []  # 保存一部电影的所有信息
            item = str(item)
            # 获取到影片的连接
            list = re.findall(findlist, item)[0]  # 前面是正则表达式，后面是被校验的字符串
            data.append(list)
            imgsrc = re.findall(findimgsrc, item)[0]
            data.append(imgsrc)
            title = re.findall(findtitle, item)
            if len(title) == 2:
                title1 = title[0]
                data.append(title1)
                title2 = title[1].replace("/", "")  # 去掉无关符号
                data.append(title2)
            elif len(title) == 1:
                title3 = title[0]
                data.append(title3)
                data.append(' ')  # 留空
            pingfen = re.findall(findpingfen, item)[0]
            data.append(pingfen)
            people = re.findall(findpeople, item)[0]
            data.append(people)
            gaikuang = re.findall(findgaikuang, item)
            if len(gaikuang) > 0:
                gaikuang1 = gaikuang[0].replace("。", "")
                data.append(gaikuang1)
            else:
                data.append(" ")
            content = re.findall(findcontent, item)[0]
            content = re.sub('<br(\s*)?/>(\s*)?', '', content)
            data.append(content.strip())  # 去掉前后的空格
            datalist.append(data)
    return datalist


# 得到指定一个url的网页内容
def askurl(url):
    # 模拟浏览器头部信息，向豆瓣服务器发送消息
    head = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"}
    # 用户代理，告诉豆瓣服务器，我们是什么类型的机器，浏览器（本质上告诉他，我们接收什么水平的文件
    req = urllib.request.Request(url, headers=head)  # 发送请求
    try:
        response = urllib.request.urlopen(req)  # 取得响应
        html = response.read().decode("utf-8")  # 获得网页内容
    except urllib.error.URLError as i:
        if hasattr(i, "code"):
            print(i.code)
        if hasattr(i, "reason"):
            print(i.reason)

    return html


# 3.保存数据
def savedata(datalist, savepath):
    workbook = xlwt.Workbook(encoding="utf-8")
    worksheet = workbook.add_sheet('豆瓣电影top250', cell_overwrite_ok=True)  # 创建工作表，cell覆盖以前内容
    col = ("影片链接", "影片图片链接", "影片中文名", "影片外国名", "影片评分", "影片评价人数", "网页概况", "影片的相关内容")
    for i in range(0, 8):
        worksheet.write(0, i, col[i])
    for i in range(0, 250):
        print("第%d条" % i)
        data = datalist[i]
        for j in range(0, 8):
            worksheet.write(i + 1, j, data[j])

    workbook.save(savepath)


if __name__ == '__main__':
    main()
